<template>
    <div class="page-controller">
      <FISearchForm
        class="box-radius2"
        ref="ruleFormRef"
        :id="`inqu_${tableId}`"
        :searchNum="searchItemCount"
        v-model:form-value="state.query"
        :table-column="columns"
        :wrapperSpan="searchWrapperSpan"
        @submit="searchFn"
      >
        <el-col :span="searchWrapperSpan" class="flex-center">
          <FIFormItem prop="endTimeBegin" label="流程名称">
            <FIInput v-model="state.query.endTimeBegin" clearable />
          </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
            <FIFormItem prop="endTimeEnd" label="节点名称">
                <FIInput v-model="state.query.endTimeEnd" clearable />
            </FIFormItem>
        </el-col>
        <el-col :span="searchWrapperSpan" class="flex-center">
            <FIFormItem prop="starter" label="发起业务">
                <FIInput v-model="state.query.starter" clearable />
            </FIFormItem>
        </el-col>
      </FISearchForm>
      <div class="margin-bottom20"></div>
      <FITable
        ref="tableRef"
        class="box-radius2"
        title="记录集"
        :id="`result_${tableId}`"
        :readonly="false"
        :data="state.dataList"
        primaryKey="id"
        :rowNo="true"
        v-model:columns="columns"
        :insertable="true" 
        :isLoading="isTableLoading"
        :saveSuccessful="saveSuccessful"
        :pageConfig="pageConfig"
        @row-add-save="addRowSave"
        @table-refresh="searchFn"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handleCurrentChange"
        @action-click="actionClick"
      >
        <template #headerBtn>
            <el-button type="primary">删除</el-button>
        </template>
      </FITable>
    </div>
  </template>
  <script lang="ts" setup>
  import { reactive, onMounted, ref, computed, watch } from 'vue'
  import FISearchForm from '@/components/FISearchForm.vue'
  import FIFormItem from '@/components/FIFormItem.vue'
  import FIInput from '@/components/FIInput.vue'
  import FIButton from '@/components/FIButton.vue'
  import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
  import FITable from '@/components/FITable/index.vue'
  import FISelect from '@/components/FISelect/index.vue'
  import menuList from '../../user/authorityMaint/components/menuList'
  import { apiRequestPost } from '@/api/globalApi.js'
  import { ElMessage } from 'element-plus'
  import { useMessage, useMessageBox } from '@/hooks/message'
  import type { PageConfig, Column } from '@/types/components'
  import { useRoute } from 'vue-router'
  import { initSearchData } from '@/utils/common'
  import { getQueryTableCache } from '@/utils/cacheUtils'
  import { apiQueryAuth, apiDeleteAuth } from '@/api/modules/EW.js'
  const route = useRoute()
  const menuShow = ref(false)
  const searchWrapperSpan = 8
  const showSearch = ref(true)
  const isTableLoading = ref(false)
  // 页面编码
  const tableId = 'usersAudit'
  // 保存成功按钮状态，默认不展示底部保存，取消按钮
  const saveSuccessful = ref(false)
  const tableRef = ref(null)
  
  const state = reactive({
    query: {
      endTimeBegin:'',
      endTimeEnd:'',
      startDeptId:'',
      starter:'',
      current: 1,
      size: 10,
    },
    dataList: [],
  })
  const pageConfig: PageConfig = reactive({
    total: 0,
    currentPage: 1,
  })
  const columns: Column[] = reactive([
    {
      label: '流程代码',
      prop: 'processName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '流程名称',
      prop: 'productName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '节点代码',
      prop: 'recCreateTime',
      align: 'center',
      editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '节点名称',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '发起业务',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '发起应用',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '发起模块',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '人员',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    {
      label: '岗位',
      prop: 'contractName',
      align: 'center',
      editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
    },
    
   

    // {
    //   label: '',
    //   prop: 'action',
    //   actionConfig: [{ id: 'isTop', type: 'top' }],
    // },
  ])
  
  const checkedRows = ref([])
  const treeVal = ref([])
  const handleSelectionChange = (e) => {
    checkedRows.value = e
  }
  const handleSizeChange = (e) => {
    pageConfig.pageSize = e
    pageConfig.currentPage = 1
    searchFn()
  }
  const selectNode = (data) => {
    treeVal.value = data
  
    // searchFn('query','',data.payload.nodeId)
  }
  const saveMenuFunc = () => {
    console.log(treeVal,'treeVal')
    let list = treeVal.value.map((v) => {
      return v.payload.resourceEname
  
    })
      let newArr = list.filter(item => item && item.trim())
  
    apipageFavorInsert(newArr)
      .then((res) => {
        if (res.data.success) {
          useMessage().success(res.data.message)
  
          menuShow.value = false
  
          // searchFn('query','',activeName.value == '3' ? editData.value.postId : editData.value.groupId)
        }
      })
      .catch((error: any) => {})
  }
  //删除事件
  const deleteRow = () => {
    if (!checkedRows.value.length) {
      useMessage().warning('请选择一条数据')
      return
    }
    let ids = []
    Array.isArray(checkedRows.value) &&
      checkedRows.value.forEach((item: any) => {
        if (item?.id) ids.push(item?.id)
      })
    isTableLoading.value = true
    apiDeleteAuth(ids)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          useMessage().success(res.data.message)
          searchFn()
        }
      })
      .catch((error: any) => {
        useMessage().error(error.data.message)
        isTableLoading.value = false
      })
  }
  //操作
  const actionClick = (item, rowData, btnInfo) => {
    console.log(rowData, 'rowData')
    useMessageBox()
      .confirm(`您确认要置顶吗？`, '提示')
      .then(() => {
        apiExchangeSortIndex([rowData.id,0])
            .then((res) => {
              console.log(res, 'res123')
              if (res.data.success) {
                useMessage().success(res.data.message)
                searchFn()
              } else {
              }
            })
            .catch((error: any) => {})
      })
      .catch(() => {})
  }
  const handleCurrentChange = (e) => {
    pageConfig.currentPage = e
    searchFn()
  }
  // 隐藏搜索项有值的个数
  const searchItemCount = computed(() => {
    let filledCount = 0
    const outKeys = ['dynamicParams', 'orderbyParams', 'size', 'current']
    // 下面是从第三项起计算常规搜索条件有值个树
    // 获取state.query的所有keys
    const queryKeys = Object.keys(state.query).filter((key) => !outKeys.includes(key))
    if (queryKeys.length < 3) return 0
    // 从第三项开始计算
    queryKeys.slice(2).forEach((key) => {
      if (state.query[key] !== '' && state.query[key] !== null) {
        filledCount++
      }
    })
    return filledCount
  })
  const searchFn = (type?: string, columnsVal?: any) => {
    const obj = initSearchData(type, columnsVal, columns, state.query)
    state.query = obj.queryData
    columns.values = obj.columns
  
    state.query.current = pageConfig.currentPage
    isTableLoading.value = true
    if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
    apiQueryAuth(state.query)
      .then((res) => {
        console.log(res, 'res')
        isTableLoading.value = false
        if (res.data.success) {
          state.dataList = res.data.data.result
          // console.log(state.dataList)
            pageConfig.pageSize = Number(res.data.data.size)
            pageConfig.total = Number(res.data.data.count)
        } else {
          // ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
        // 处理错误
      })
  }
  const handleSave = () => {
    isTableLoading.value = true
    saveSuccessful.value = false
    apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
      .then((res) => {
        isTableLoading.value = false
        if (res.data.success) {
          // saveSuccessful.value = true
          tableRef.value.clearSelection()
          searchFn()
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch((error: any) => {
        isTableLoading.value = false
      })
  }
  //   const exportRow = () => {
  //     apiGroupUserExport(state.query)
  //   }
  const ruleFormRef = ref(null)
  
  const addRowSave = (data) => {
    handleSave()
  }
  onMounted(() => {
    // 获取查询条件缓存
    const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
    if (cachedQuery) state.query = cachedQuery
    if (columns) columns.values = cachedColumns
    searchFn()
  })
  </script>
  <style lang="less" scoped></style>
  